import Panel from "./../../elements/Panel";
import Header from "./../../components/Header";
import Modal from "./../../components/Modal/";
import {connect} from "react-redux";
import CONFIG from "./../../libs/config";
import {Lang, Fetch} from "./../../libs/";
import {URL, md5Url} from "./../../libs/Url";
import Label from "./../../components/FormLabel";
import FormGroup from "./../../components/FormGroup";
import FormItem from "./../../components/FormItem";
import FormItemType from "./../../components/FormItemType";
import InputGroup from "./../../components/InputGroup";
import Selected from "./../../components/SelectItem";
import BreadcrumbNavigation from "./../../components/BreadcrumbNavigation";
import {fetch, fetchUser} from "../../actions";
import {SUBJECT, PAGE_SUBJECT} from "./../../actions/subject";
import {html_encode, html_decode} from './../../libs/util';
const AddNews = React.createClass({
    getInitialState(){

        const self = this;
        this.isUpdate = this.props.router.params.id;
        this.form = [
            // {
            //     name: 'classid',
            //     label: Lang.NEWS_CREATE.label.class,
            //     value: '',
            //     tips: '',
            //     type: FormItemType.MODAL_CHECK_BOX,
            //     onchange: function (index, content) {
            //         self.setState({
            //             form: [
            //                 ...self.state.form.slice(0, index),
            //                 Object.assign({}, self.state.form[index], {
            //                     value: content,
            //                     tips: content.length ? '' : '该项必填',
            //                 }),
            //                 ...self.state.form.slice(index + 1),
            //             ]
            //         });
            //     }
            // },
            {
                name: 'classifyid',
                label: Lang.NEWS_CREATE.label.category,
                value: '',
                tips: '',
                required: true,
                inits: [],
                type: FormItemType.SELECT,
                onchange: function (index, content) {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                value: content,
                                tips: content.length ? '' : '该项必填',
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    });
                }
            },
            {
                name: 'title',
                label: Lang.NEWS_CREATE.label.title,
                placeholder: '',
                required: true,
                value: '',
                tips: '',
                type: FormItemType.INPUT,
                onchange: function (index, content) {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                value: content,
                                tips: content.length ? '' : '该项必填',
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    });
                }
            },
            {
                name: 'summary',
                label: Lang.NEWS_CREATE.label.summary,
                value: '',
                placeholder: '',
                tips: '',
                onchange: function (index, content) {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                value: content,
                                tips: content.length ? '' : Lang.NEWS_CREATE.tip,
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    });
                }
            },
            {
                name: 'fileids',
                label: Lang.NEWS_CREATE.label.thum,
                value: '',
                placeholder: '',
                tips: '',
                type: FormItemType.UPLOAD,
                onchange: function (index, content) {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                value: content,
                                tips: content.length ? '' : Lang.NEWS_CREATE.tip,
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    });
                }
            },
            {
                name: 'publisher',
                label: Lang.NEWS_CREATE.label.author,
                value: '',
                placeholder: '',
                tips: '',
                onchange: function (index, content) {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                value: content,
                                tips: content.length ? '' : Lang.NEWS_CREATE.tip,
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    });
                }
            },
            {
                name: 'source',
                label: Lang.NEWS_CREATE.label.source,
                value: '',
                placeholder: '',
                tips: '',
                onchange: function (index, content) {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                value: content,
                                tips: content.length ? '' : Lang.NEWS_CREATE.tip,
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    });
                }
            },
            {
                name: 'content',
                label: Lang.NEWS_CREATE.label.content,
                placeholder: '',
                value: '',
                required: true,
                tips: '',
                type: FormItemType.EDITOR,
                onchange: function (index, content) {
                    if (self.state.form[index].value == content) {
                        return;
                    }
                    console.log(content)
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                value: content,
                                tips: content.length ? '' : Lang.NEWS_CREATE.tip,
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    })
                }
            }
        ];

        const isUpdate = this.props.router.params.id;
        return {
            open: false,
            selected: '',
            form: isUpdate ? [] : self.form,
            tips: {}
        }
    },
    setchange(index, content){
        const self = this;
        self.setState({
            form: [
                ...self.state.form.slice(0, index),
                Object.assign({}, self.state.form[index], {
                    value: content,
                    tips: content.length ? '' : Lang.NEWS_CREATE.tip,
                }),
                ...self.state.form.slice(index + 1),
            ]
        })
    },
    componentDidMount() {
        const self = this;
        if (this.props.router.params.id) {
            Fetch(URL.NEWS_GET, {body: {newsid: this.props.router.params.id}})
                .then((res)=> {
                    let news_ = res.news;
                    self.form = self.form.map(item=> {
                        item.value = news_[item.name];
                        return item;
                    });
                    console.log(self.form);
                    self.setState({
                        form: self.form,
                    });
                })
                .catch(e=> {
                    console.log(e);
                })
        }
        const {dispatch} = this.props;
        dispatch(fetchUser(SUBJECT.NEWS_CATEGORY));
        dispatch(fetch({url: URL.CATEGORY_FIND}))
    },
    componentWillReceiveProps(nextProps){
        var add = this.props[md5Url.NEWS_ADD];

    },
    onsubmit(){
        const {dispatch, user} = this.props, isUpdate = this.props.router.params.id;
        const self = this;

        let data_category = this.props[md5Url.CATEGORY_FIND] || {};
        (!data_category.list && (data_category.list = []));
        if (!data_category.list.length)return alert('分类未设置');
        var form = {}, tmp = false;
        self.state.form.forEach((item, index)=> {
            if (tmp)
                return tmp;
            if (item.required && item.value.length == 0) {
                // if (index == 0) {
                //     form[item.name] = user['class'].map(item=> {
                //         return item.classid
                //     }).toString()
                // } else
                if (index == 0) {
                    form[item.name] = data_category.list[0].id;
                } else {
                    tmp = true;
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                tips: Lang.NEWS_CREATE.tip,
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    })
                }

            } else {
                form[item.name] = item.value
            }
        });
        console.log(form);
        if (Object.keys(form).length == self.state.form.length) {
            // form.classid = form.classid.slice(1);
            // if (form.classid.length - 1 == form.classid.lastIndexOf(',')) {
            //     form.classid = form.classid.slice(0, form.classid.length - 1);
            // }
            form.url = URL.NEWS_ADD;
            if (isUpdate) {
                form.newsid = isUpdate;
            }
            Fetch(isUpdate ? URL.NEWS_UPDATE : URL.NEWS_ADD, {body: form, method: 'POST'})
                .then(data=> {
                    alert(isUpdate ? '更新成功!' : '创建成功!');
                    if (!isUpdate) {
                        self.props.router.push(CONFIG.MENUS_ABSOLUTE.NEWS);
                    }
                })
                .catch(e=> {
                    alert(isUpdate ? '更新失败!' : '更新失败!');
                    console.log(e)
                })
        }
    },
    render(){
        const self = this;
        const {user, dispatch}  = this.props;
        const form = this.props[PAGE_SUBJECT.NEWS_ADD].form;

        const data_category = self.props[md5Url.CATEGORY_FIND] || {};
        // console.log(data_category);
        (!data_category.list && (data_category.list = []));

        return (
            <div>
                <BreadcrumbNavigation navs={[
                    {url: CONFIG.MENUS_ABSOLUTE.HOME, label: Lang.menus.HOME},
                    {url: CONFIG.MENUS_ABSOLUTE.NEWS, label: Lang.menus.NEWS_LIST},
                    {label: this.props.router.params.id ? Lang.menus.NEWS_UPDATE : Lang.menus.NEWS_CREATE}
                ]}></BreadcrumbNavigation>
                <Panel>
                    <Header>{this.props.router.params.id ? Lang.menus.NEWS_UPDATE : Lang.menus.NEWS_CREATE}</Header>
                    <div className="form-horizontal">
                        {
                            self.state.form.map((item, index)=> {
                                if (item.type == FormItemType.MODAL_CHECK_BOX) {
                                    return <FormItem {...item} key={index}>
                                        <div className="homeword">
                                            {
                                                user.class.map((item_, idex)=> {
                                                    {/*item_.checked = self.state.form[index].value.indexOf(item_.classid) > -1*/
                                                    }
                                                    item_.checked = self.state.form[index].value
                                                            .indexOf(item_.classid) > -1 ||
                                                        (!self.state.form[index].value.replace(',', '').length);
                                                    return <Selected onremove={()=> {
                                                        item.onchange(index, self.state.form[index].value.replace(item_.classid + ',', ''));
                                                    }} key={idex} {...item_} />
                                                })
                                            }
                                            <button className="btn btn-default btn-sm " onClick={()=> {
                                                this.setState({open: true})
                                            }} type="button"><i className="fa fa-hand-o-up"></i> {Lang.NEWS_CREATE.set}
                                            </button>
                                        </div>
                                        <Modal open={self.state.open}>
                                            <Modal.Header onclose={()=> {
                                                self.setState({open: false, selected: ''})
                                            }
                                            }>{Lang.NEWS_CREATE.choose}</Modal.Header>
                                            <Modal.Body >
                                                <form className="form-horizontal">
                                                    <div className="form-group">
                                                        <label
                                                            className="col-sm-3 control-label">{Lang.NEWS_CREATE.grade}：</label>
                                                        <div className="col-sm-9">
                                                            {
                                                                user.class.map((item_, idex)=> {
                                                                    return (
                                                                        <label className="checkbox-inline" key={idex}>
                                                                            <input type="checkbox"
                                                                                   checked={(self.state.form[index].value.concat(self.state.selected)).indexOf(item_.classid) > -1}
                                                                                   onClick={(e)=> {
                                                                                       if (e.target.checked) {
                                                                                           self.setState({
                                                                                               selected: self.state.selected + item_.classid + ','
                                                                                           })
                                                                                       } else {
                                                                                           self.setState({
                                                                                               selected: self.state.selected.replace(item_.classid + ',', '')
                                                                                           });
                                                                                       }
                                                                                   }}/>
                                                                            {item_['class'].name} </label>
                                                                    )
                                                                })
                                                            }
                                                        </div>
                                                    </div>
                                                </form>
                                            </Modal.Body>
                                            <Modal.Footer onclose={()=> {
                                                self.setState({open: false, selected: ''})
                                            }
                                            } onconfirm={()=> {
                                                console.log(_.union(self.state.form[index].value.split(','),
                                                    self.state.selected.split(',')))
                                                item.onchange(index, _.union(self.state.form[index].value.split(','),
                                                        self.state.selected.split(',')).join(',') + ',')
                                                self.setState({open: false, selected: ''})
                                            }
                                            }/>
                                        </Modal>
                                    </FormItem>
                                } else if (item.type == FormItemType.SELECT) {
                                    return <FormItem {...item} key={index}>
                                        <select className="form-control" defaultValue={item.value} onChange={(e)=> {
                                            item.onchange(index, e.target.value)
                                        }}>
                                            {
                                                data_category.list.map(function (item_, index) {
                                                    var selected = false
                                                    {/*if (item_.id == item.value) {*/}
                                                        {/*selected = true;*/}

                                                    {/*}*/}
                                                    return <option  value={item_.id}
                                                                   key={index}>{item_.name}</option>
                                                })
                                            }
                                        </select>
                                    </FormItem>
                                } else {
                                    return <FormItem index={index} {...item} key={index}></FormItem>
                                }
                            })
                        }
                        <FormGroup>
                            <Label></Label>
                            <InputGroup>
                                <button onClick={self.onsubmit} className="btn btn-success" type="submit">
                                    {Lang.NEWS_CREATE.save}{this.props[PAGE_SUBJECT.NEWS_ADD].isFetching ? '...' : ''}</button>
                            </InputGroup>
                        </FormGroup>
                    </div>
                </Panel>
            </div>
        )
    }
});
function select(state) {
    return {
        user: state.user.user,
        [md5Url.CATEGORY_FIND]: state.fetchBySubject[md5Url.CATEGORY_FIND],
        [md5Url.NEWS_ADD]: state.fetchBySubject[md5Url.NEWS_ADD],
        [PAGE_SUBJECT.NEWS_ADD]: state.pageBySubject[PAGE_SUBJECT.NEWS_ADD]
    }
}
export default connect(select)(AddNews)
